<template>
  <BottomDrawer
    :visible="visible"
    :width="607"
    :showFooter="false"
    @close="onCancel"
  >
    <div class="register-dialog-header-bar">
      <div class="header-bar-left">
        <div class="tab-btns">
          <!-- <div
            :class="['tab-btn', activeTab === 'register' ? 'active' : '']"
            
            @click="activeTab = 'register'; formDatas.visitDate = dayjs(new Date()).format('YYYY-MM-DD')"
            
          >
            <img
              src="@/assets/icon/icon_guahao.svg"
              class="tab-icon"
              v-show="activeTab == 'register'"
            />
            <img
              v-show="activeTab != 'register'"
              src="@/assets/icon/icon_guahao-active.svg"
              class="tab-icon"
            />挂号
          </div> -->
          <div
            :class="['tab-btn', activeTab === 'reserve' ? 'active' : '']"
            @click="activeTab = 'reserve'"
          >
            <img
              v-show="activeTab === 'reserve'"
              src="@/assets/icon/icon_yuyue-active.svg"
              class="tab-icon"
            />
            <img
              v-show="activeTab != 'reserve'"
              src="@/assets/icon/icon_yuyue.svg"
              class="tab-icon"
            />
            预约
          </div>
        </div>
      </div>
      <div class="header-bar-right">
        <div class="read-card-btn" @click="readCard">
          <img src="@/assets/icon/icon_duka.svg" class="tab-icon" /> 读卡
          {{ deptName }}
        </div>
      </div>
    </div>
    <div class="register-dialog-form">
      <el-form
        :model="formDatas"
        :inline="true"
        label-width="55px"
        size="large"
        class="custom-register-form"
      >
        <el-form-item label="患者" required>
          <div style="position: relative; display: flex">
            <div style="position: relative">
              <el-input
                v-model="formDatas.patientName"
                clearable
                @focus="querySearchAsyncPatientPhone('patientName')"
                @blur="userSelectDomblur"
                @input="querySearchAsyncPatientPhone('patientName')"
                placeholder="患者"
                style="width: 144px"
              />
              <userSelect
                ref="userSelectDom"
                @select="handleSelect1"
              ></userSelect>
            </div>
            <el-select
              v-model="formDatas.patientGender"
              :disabled="!!formDatas.patientId"
              placeholder="性别"
              style="width: 80px; margin-left: 10px"
            >
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
              <el-option label="未知" value="3" />
            </el-select>
            <div style="position: relative">
              <el-input
                v-model="formDatas.patientPhone"
                placeholder="电话"
                clearable
                @focus="querySearchAsyncPatientPhone('patientPhone')"
                @blur="userSelectDomblur"
                @input="querySearchAsyncPatientPhone('patientPhone')"
                style="width: 230px; margin-left: 10px"
              />
              <userSelect
                ref="userSelectDomPhone"
                @select="handleSelect1"
              ></userSelect>
            </div>
          </div>

          <!-- <el-autocomplete
            v-model="" clearable
            :fetch-suggestions="querySearchAsyncPatientPhone" :disabled="!!formDatas.patientId"
            placeholder="电话" style="width: 121px;margin-left: 5px;"
            @select="handleSelect1" @clear="handleSelect1"
          /> -->
        </el-form-item>
        <el-form-item label="信息">
          <!-- <el-input
            v-model="formDatas.idCard" :disabled="!!formDatas.patientId"
            placeholder="身份证"
            style="width: 220px; height: 46px"
          /> -->
          <div style="position: relative; display: flex">
            <div style="position: relative">
              <el-input
                v-model="formDatas.idCard"
                @change="idCardToBirthday"
                clearable 
                @focus="querySearchAsyncPatientPhone('idCard')"
                @blur="userSelectDomblur"
                @input="querySearchAsyncPatientPhone('idCard')"
                placeholder="身份证"
                style="width: 234px"
              />
              <userSelect
                ref="userSelectDom2"
                @select="handleSelect1"
              ></userSelect>
            </div>
            <div class="blood-pressure-input-container">
              <el-input
                type="text"
                class="pressure-input"
                style="width: 90px; height: 28px"
                :disabled="!!formDatas.patientId"
                v-model="formDatas.ageYear"
              />
              <span class="separator">岁</span>
              <el-input
                type="text"
                class="pressure-input"
                style="width: 90px; height: 28px"
                :disabled="!!formDatas.patientId"
                v-model="formDatas.ageMonth"
              />
              <span class="unit">月</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            type="date"
            v-model="formDatas.solarBirthday"
            placeholder="阳：年/月/日"
            :disabled="!!formDatas.patientId"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 234px"
          >
          </el-date-picker>
          <el-date-picker
            type="date"
            v-model="formDatas.lunarBirthday"
            placeholder="阴：/月/日"
            format="YYYY-MM-DD"
            :disabled="!!formDatas.patientId"
            value-format="YYYY-MM-DD"
            style="width: 230px; margin-left: 10px"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="日期">
          <el-select
            v-if="activeTab === 'register'"
            v-model="formDatas.visitDate"
            style="width: 475px"
            @change="visitDateChange"
            placeholder="日期"
            :disabled="activeTab === 'register'"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="(item, index) in timeList"
              :key="index"
            />
          </el-select>
          <el-select
            v-else
            v-model="formDatas.visitDate"
            style="width: 475px"
            @change="visitDateChange"
            placeholder="日期"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="(item, index) in timeList2"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="医生"
          required
          style="position: relative"
          class="form-item form-item-doctor"
        >
          <el-input
            placeholder="医生"
            v-model="formDatas.doctorName"
            style="width: 215px"
            :disabled="formDatas.visitDate == ''"
            @focus="showDoctorList = true"
          >
          </el-input>
          <div style="position: absolute; top: 0; left: 0">
            <DoctorSelectList
              v-if="showDoctorList"
              ref="doctorListRef"
              :time="formDatas.visitDate"
              @select="onDoctorSelect"
              style="position: sticky; top: 48px; left: 0; z-index: 10"
            />
          </div>

          <div v-if="activeTab === 'register'">
            <el-select
              v-model="formDatas.visitPeriod"
              style="width: 260px; margin-left: 0px"
              placeholder="时间段"
              :disabled="!formDatas.doctorId"
            >
              <el-option
                :label="item.text"
                :value="item.value"
                :disabled="item.available == 0"
                v-for="(item, index) in periodList"
                :key="index"
              />
            </el-select>
          </div>
          <div style="display: flex" v-else>
            <el-select
              v-model="formDatas.visitPeriod"
              placeholder="时间段"
              :disabled="!formDatas.doctorId"
              @change="periodList2DataFun"
              style="width: 95px"
            >
              <el-option
                :label="item.text"
                :value="item.value"
                :disabled="item.available == 0"
                v-for="(item, index) in periodList"
                :key="index"
              />
            </el-select>
            <el-select
              v-model="formDatas.visitSeqNo"
              placeholder="时间段"
              :disabled="!formDatas.doctorId || formDatas.visitPeriod == ''"
              style="width: 165px"
            >
              <el-option
                :label="
                  item.visitSeqNo + '   ' + item.startTime + '~' + item.endTime
                "
                :value="item.visitSeqNo"
                v-for="(item, index) in periodList2"
                :key="index"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="费用">
          <el-select
            v-model="formDatas.visitType"
            @change="feeData"
            :disabled="!formDatas.doctorId"
            placeholder="初诊"
            style="width: 150px"
          >
            <el-option
              :label="item.text"
              :value="item.value"
              v-for="item in visitTypeEnum"
              :key="item.value"
            />
          </el-select>
          <el-select
            v-model="formDatas.regType"
            @change="feeData"
            :disabled="!formDatas.doctorId"
            placeholder="就诊类型"
            style="width: 150px"
          >
            <el-option
              :label="item.text"
              :value="item.value"
              v-for="item in regStatusEnum"
              :key="item.value"
            />
          </el-select>
          <el-input
            v-model="formDatas.regFee"
            style="width: 175px"
            placeholder="挂号类型"
            :formatter="(value:any) => `￥ ${(value / 100).toFixed(2)}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            disabled
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formDatas.remark"
            placeholder="备注"
            style="width: 475px"
          />
        </el-form-item>
        <el-form-item label="" class="form-item">
          <el-button style="margin-left: 380px" @click="onCancel"
            >取消</el-button
          >
          <el-button type="primary" @click="onConfirm">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </BottomDrawer>
</template>

<script setup lang="ts">
import { getDoctorDict } from '@/api/register';
import { reactive } from 'vue';
import DoctorSelectList from './DoctorSelectList.vue';
import stores from '@/store';
import dayjs from 'dayjs';
import type { PatientInfo } from '@/types/patient';
import { addRegister, getRemainList } from '@/api/registerList';
const visible = defineModel<boolean>('visible', { default: false });
import type { DoctorResData } from '@/types/registerList';
const useBaseData = stores.useBaseDataStore();
import { getPatientList } from '@/api/patient';
import { useIDCardReader, type IDCardInfo } from '@/utils/idCardReader';

import userSelect from './userSelect.vue';
const userSelectDom = ref<InstanceType<typeof userSelect> | null>(null);
const userSelectDomPhone = ref<InstanceType<typeof userSelect> | null>(null);
const userSelectDom2 = ref<InstanceType<typeof userSelect> | null>(null);

const timeList = ref<any>([]);
const timeList2 = ref<any>([]);
const deptName = ref('');
const formDatas = ref<any>({
  patientName: '',
  patientGender: '1',
  patientId: '',
  doctorName: '',
  patientPhone: '',
  idCard: '',
  ageYear: null,
  ageMonth: null,
  lunarBirthday: '',
  solarBirthday: '',
  visitDate: '',
  visitPeriod: '',
  regMethod: '',
  regChannel: '1',
  doctorId: '',
  visitType: '',
  regType: '',
  regFee: null,
  visitSeqNo: '',
  remark: '',
});
import { ArrowDownBold } from '@element-plus/icons-vue';
const patientList = ref<PatientInfo[]>([]);

/**
 * 读取身份证卡片信息
 */
const readCard = async () => {
  const cardReader = useIDCardReader();
  const loadingMsg = ElMessage({
    message: '正在读取身份证，请将身份证放在读卡器上...',
    type: 'info',
    duration: 0,
  });

  try {
    await cardReader.readCard(
      (data: IDCardInfo) => {
        loadingMsg.close();
        ElMessage.success('读卡成功');

        // 清空 patientId，表示新建患者
        formDatas.value.patientId = '';

        // 回显姓名
        formDatas.value.patientName = data.name || '';

        // 回显性别（转换为系统格式：1-男，2-女，3-未知）
        if (data.gender === '男') {
          formDatas.value.patientGender = '1';
        } else if (data.gender === '女') {
          formDatas.value.patientGender = '2';
        } else {
          formDatas.value.patientGender = '3';
        }

        // 回显身份证号
        formDatas.value.idCard = data.idNumber || '';

        // 根据身份证号自动计算生日
        if (data.idNumber) {
          idCardToBirthday();
        }
      },
      (error: string) => {
        loadingMsg.close();
        //ElMessage.error(error || '读卡失败，请重试');
      },
      15000 // 15秒超时
    );
  } catch (error) {
    loadingMsg.close();
    const errorMsg = error instanceof Error ? error.message : '读卡异常';
    //ElMessage.error(errorMsg);
  }
};

/**
 * 计算年龄
 */
const calculateAge = (birthday: string) => {
  const birthDate = dayjs(birthday);
  const currentDate = dayjs();

  const years = currentDate.diff(birthDate, 'year');
  const months = currentDate.diff(birthDate, 'month') % 12;

  formDatas.value.ageYear = years;
  formDatas.value.ageMonth = months;
};
//身份证号转生日
import { getLunar } from 'chinese-lunar-calendar';
const idCardToBirthday = () => {
  formDatas.value.idCard = formDatas.value.idCard.replace(/[^a-zA-Z0-9]/g, '');
  if (formDatas.value.idCard == '') {
    return;
  }

  if (/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(formDatas.value.idCard)) {
    const birthYear = formDatas.value.idCard.substring(6, 10);
    const birthMonth = formDatas.value.idCard.substring(10, 12);
    const birthDay = formDatas.value.idCard.substring(12, 14);
    const solarDate = `${birthYear}-${birthMonth}-${birthDay}`;
    formDatas.value.solarBirthday = solarDate;
    calculateAge(solarDate);

    try {
      const lunarDate = getLunar(birthYear, birthMonth, birthDay);

      let yesr: number = 0;
      if (lunarDate.lunarMonth > birthMonth) {
        yesr = Number(birthYear) - 1;
      } else {
        yesr = Number(birthYear);
      }

      // 410704199604130019

      formDatas.value.lunarBirthday = `${yesr}-${
        lunarDate.lunarMonth < 10
          ? '0' + lunarDate.lunarMonth
          : lunarDate.lunarMonth
      }-${
        lunarDate.lunarDate < 10
          ? '0' + lunarDate.lunarDate
          : lunarDate.lunarDate
      }`;

      //console.log(formDatas.value.lunarBirthday);
      //console.log(lunarDate.lunarMonth);
    } catch (error) {
      //console.log(error, 'error');
    }

    // const lunar = new Lunar(formDatas.value.solarBirthday);
    // formDatas.value.lunarBirthday = lunar.getSolar().getFullYear() + '-' + lunar.getSolar().getMonth() + '-' + lunar.getSolar().getDate();
  } else {
    //console.log('身份证格式错误');
  }
};

//获取医生挂号配置
const releaseAheadDay = ref<number>(1);
const getDoctorDictData = async () => {
  try {
    const response = await getDoctorDict();
    releaseAheadDay.value = Number(response.data.releaseAheadDay) + 1 || 1;
  } catch (error) {
    //console.error('获取医生字典失败:', error);
  }
};
getDoctorDictData();
//选择时间后
const visitDateChange = () => {
  formDatas.value.doctorName = '';
  ysObj.value = null;
  deptName.value = '';
  periodList.value = [];

  formDatas.value.visitPeriod = '';
  formDatas.value.visitSeqNo = '';

  formDatas.value.visitType = '';
  formDatas.value.regType = '';
  formDatas.value.regFee = '';
};

const feeData = () => {
  //1 初诊 2 复诊
  //1 普通 2 急诊
  if (formDatas.value.visitType == '1') {
    formDatas.value.regFee = ysObj.value.firstVisitFee || 0;
  } else if (formDatas.value.visitType == '2') {
    formDatas.value.regFee = ysObj.value.followUpFee || 0;
  }
  if (formDatas.value.regType == '1') {
    formDatas.value.regFee = ysObj.value.appointmentFee || 0;
  } else if (formDatas.value.regType == '2') {
    formDatas.value.regFee = ysObj.value.emergencyFee || 0;
  }
};
const activeTab = ref('register');
const props = defineProps<{
  showRegisterDialog: boolean;
}>();

// 切换到“挂号”标签
const onClickRegisterTab = () => {
  activeTab.value = 'register';
  formDatas.value.visitDate = dayjs(new Date()).format('YYYY-MM-DD');
  // getRemainListApi
  feeData();  

 if(formDatas.value.doctorName){
    let formData = {
      visitDate: formDatas.value.visitDate,
      doctorName: formDatas.value.doctorName,
    };
    fetchRemainAndSetDoctorInfo(formData);
  }
};

// 切换到“预约”标签
const onClickReserveTab = () => {
  activeTab.value = 'reserve';
  // 与原内联逻辑保持一致，直接取 timeList2 的第一个元素
  formDatas.value.visitDate = timeList2.value[0];
  feeData();  

  if(formDatas.value.doctorName){
    let formData = {
      visitDate: formDatas.value.visitDate,
      doctorName: formDatas.value.doctorName,
    };
    fetchRemainAndSetDoctorInfo(formData);
  }
 
};

watch(
  () => props.showRegisterDialog,
  (val) => {
    visible.value = val;
    timeList.value = [];
    if ((releaseAheadDay?.value ?? 0) > 0) {
      //console.log(releaseAheadDay?.value);
      for (let index = 0; index < releaseAheadDay?.value; index++) {
        if (index == 0) {
        } else {
          let today = dayjs();
          let dateIn14Days = today.add(index, 'day');
          timeList.value.push(dateIn14Days.format('YYYY-MM-DD'));
        }
      }
    }

    formDatas.value = {
      patientName: '',
      patientGender: '1',
      doctorName: '',
      patientPhone: '',
      patientId: '',
      idCard: '',
      ageYear: null,
      ageMonth: null,
      lunarBirthday: '',
      solarBirthday: '',
      visitDate:activeTab.value == 'register' ? timeList.value[0] : timeList2.value[0],
      visitPeriod: '',
      regMethod: '',
      regChannel: '1',
      doctorId: '', // 补充缺失属性
      visitType: '1', // 补充缺失属性
      regType: '1', // 补充缺失属性
      regFee: null, // 补充缺失属性
      remark: '', // 补充缺失属性
    };
  },
  { immediate: true }
);

const PatientPhoneData = ref<any>();
const querySearchAsyncPatientPhone = (name: string) => {

  if(name == 'idCard'){
    formDatas.value.idCard = formDatas.value.idCard.replace(/[^a-zA-Z0-9]/g, '');
  }

  if (formDatas.value[name] != '') {
    const data = {
      patientName: formDatas.value[name],
      pageNo: 1,
      pageSize: 1000000,
    };
    getPatientList(data).then((res) => {
      let results: any = res.data;
      if (results.length > 0 && name == 'patientName') {
        userSelectDom.value?.open(results);
        userSelectDomPhone.value?.close();
        userSelectDom2.value?.close();
      } else if (results.length > 0 && name == 'patientPhone') {
        userSelectDomPhone.value?.open(results);
        userSelectDom.value?.close();
        userSelectDom2.value?.close();
      } else if (results.length > 0 && name == 'idCard') {
        userSelectDom2.value?.open(results);
        userSelectDom.value?.close();
        userSelectDomPhone.value?.close();
      }
    });
  } else {
    if (formDatas.value.patientId) {
      formDatas.value.patientId = '';
      formDatas.value.patientGender = '';
      formDatas.value.ageYear = '';
      formDatas.value.ageMonth = '';
      formDatas.value.lunarBirthday = '';
      formDatas.value.solarBirthday = '';
      if (name == 'patientName') {
        formDatas.value.patientPhone = '';
        formDatas.value.idCard = '';
      }
      if (name == 'patientPhone') {
        formDatas.value.patientName = '';
        formDatas.value.idCard = '';
      }
      if (name == 'idCard') {
        formDatas.value.patientName = '';
        formDatas.value.patientPhone = '';
      }
    }

    userSelectDom.value?.close();
    userSelectDomPhone.value?.close();
    userSelectDom2.value?.close();
  }
};
const userSelectDomblur = () => {
  setTimeout(() => {
    userSelectDom.value?.close();
    userSelectDomPhone.value?.close();
    userSelectDom2.value?.close();
  }, 200);
};

const handleSelect1 = (obj: any) => {
  //console.log(obj, 'obj');

  if (obj) {
    formDatas.value.patientId = obj.patientId;
    formDatas.value.patientGender = obj.patientGender;
    formDatas.value.patientName = obj.patientName;
    formDatas.value.idCard = obj.idCard;
    formDatas.value.ageYear = obj.ageYear;
    formDatas.value.ageMonth = obj.ageMonth;
    formDatas.value.lunarBirthday = obj.lunarBirthday;
    formDatas.value.solarBirthday = obj.solarBirthday;
    formDatas.value.patientPhone = obj.patientPhone;
  }
};

//初诊类型
const visitTypeEnum = useBaseData.getEnumSelect('visitTypeEnum');
//挂号类型
const regStatusEnum = useBaseData.getEnumSelect('regTypeEnum');

const showDoctorList = ref(false);
const doctorInputRef = ref();
const emits = defineEmits(['cancel', 'confirm']);

const periodList = ref<any>();
const periodList2 = ref<any>([]);
const timeType = ref('1');
const periodList2DataFun = () => {
  periodList2.value = [];
  formDatas.value.visitSeqNo = '';
  for (let index = 0; index < periodList.value.length; index++) {
    let item = periodList.value[index];
    if (item.value == formDatas.value.visitPeriod) {
      for (let index2 = 0; index2 < item.detailList.length; index2++) {
        let element = item.detailList[index2];
        if (element.available > 0) {
          periodList2.value.push(element);
        }
      }
    }
  }
};

const ysObj = ref<any>({});
const messBox = ref<any>(true);
// 封装：根据日期/医生名获取第一条号源并设置医生信息（ysObj、doctorName、periodList 等）
const fetchRemainAndSetDoctorInfo = async (payload: {
  visitDate: string;
  doctorName: string;
}) => {
  try {
    const res = await getRemainList(payload);
     if(res.code != '200') {
        return
    } 
    const firstDept = Array.isArray(res?.data) ? res.data[0] : null;
    const info = firstDept?.remainList?.[0];
    if (!info) return null;

    // 设置界面所需信息
    ysObj.value = info;
    formDatas.value.doctorName = `${info.title}·${info.doctorName}`;
    formDatas.value.doctorId = info.doctorId;
    periodList.value = info.periodList || [];

    periodList2DataFun();
    return info;
  } catch (e) {
    //console.error('获取号源失败: ', e);
    return null;
  }
};

defineExpose<{
  open: (row: any, t: number) => void;
}>({
  open: async (row: any, t: number) => {
    visible.value = true;

    timeType.value = row.timeType;
    let formData = {
      visitDate: row.visitDate,
      doctorName: row.doctorName,
    };
    // let res = await getRemainList(formData);
    // let info = res.data[0].remainList[0];
    // periodList.value = info.periodList;
    // periodList2DataFun();
    //console.log(timeType.value);
    if (timeType.value == '1') {
      //挂号
      activeTab.value = 'register';
    } else {
      //预约
      activeTab.value = 'reserve';
      formDatas.value.visitDate = row.visitDate;
    }

    // ysObj.value = info;
    formDatas.value.doctorId = '';
    formDatas.value.doctorName = '';
    showDoctorList.value = false;
    feeData();
    nextTick(() => {
      doctorInputRef.value?.blur();
    });
    timeList.value = [];

    for (let index = 0; index < 14; index++) {
      let today = dayjs();
      let dateIn14Days = today.add(index, 'day');
      timeList.value.push(dateIn14Days.format('YYYY-MM-DD'));
    }
    //console.log(timeList.value);

    formDatas.value = {
      patientName: '',
      patientSex: '1',
      doctorName: '',
      patientPhone: '',
      patientId: '',
      idCard: '',
      ageYear: null,
      ageMonth: null,
      lunarBirthday: '',
      solarBirthday: '',
      visitDate: timeList.value[0],
      visitPeriod: '',
      regMethod: '',
      regChannel: '1',
      doctorId: '', // 补充缺失属性
      visitType: '', // 补充缺失属性
      regType: '', // 补充缺失属性
      regFee: 0, // 补充缺失属性
      remark: '', // 补充缺失属性
      ...row,
    };
    // if (!formDatas.value.visitDate || formDatas.value.visitDate == '-') {
    // }
    formDatas.value.visitDate = dayjs().add(1, 'day').format('YYYY-MM-DD');

    // formDatas.value.visitType
    //console.log(formDatas.value);
  },
});

const onDoctorSelect = (row: any) => {
  //
  if( row.remainCount <= 0 && activeTab.value != 'register' && messBox.value == true){ 
    ElMessage.error('该医生号源不足！')
    messBox.value = false;
    return;
  }

  ysObj.value = row;
  formDatas.value.doctorId = row.doctorId;
  deptName.value = row.deptName;
  formDatas.value.doctorName = row.title + '·' + row.doctorName;

  formDatas.value.visitPeriod = '';
  formDatas.value.visitSeqNo = '';
  formDatas.value.visitType = '1';
  formDatas.value.regType = '1';
  formDatas.value.regFee = '';

  periodList.value = row.periodList;

  // periodList2.value = []
  // for (let index = 0; index < periodList.value.length; index++) {
  //   let item = periodList.value[index];
  //   for (let index2 = 0; index2 < item.detailList.length; index2++) {
  //     let  element = item.detailList[index2];
  //     //console.log(element);
  //     if(element.available > 0){
  //       periodList2.value.push(element);
  //     }

  //   }
  // }

  showDoctorList.value = false;
  feeData();
  nextTick(() => {
    doctorInputRef.value?.blur();
  });
};

const doctorListRef = ref();
const handleClickOutside = (e: MouseEvent) => {
  if (!showDoctorList.value) return;
  const inputEl =
    doctorInputRef.value?.$el ||
    doctorInputRef.value?.input ||
    doctorInputRef.value;
  const listEl = doctorListRef.value?.$el || doctorListRef.value;
  if (
    (inputEl && inputEl.contains(e.target)) ||
    (listEl && listEl.contains(e.target))
  ) {
    return;
  }
  showDoctorList.value = false;
};

// const getPatientListApi = async () => {
//   const data = {
//     patientName: '',
//     pageNo: 1,
//     pageSize: 1000000,
//   };
//   let res = await getPatientList(data);
//    if(res.code != '200') {

//         return
//     } 
//   res.data.forEach((item: any) => {
//     item.value = item.patientName;
//     item.label = item.patientName;
//   });
//   patientList.value = res.data;
// };
// getPatientListApi();

onMounted(() => {
  document.addEventListener('mousedown', handleClickOutside);
});
onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleClickOutside);
});
const onCancel = () => {
  visible.value = false;
  emits('cancel');
};
const onConfirm = () => {
  if (activeTab.value === 'register') {
    formDatas.value.regMethod = '1'; //正常
  } else {
    formDatas.value.regMethod = '2'; // 预约
  }
  let data = { ...formDatas.value };
  data.doctorName = data.doctorName.split('·')[1];

  //console.log('data', deptName.value);

  addRegister(data).then((res) => {
    if (res.code === '200') {
      ElMessage.success('预约成功');
      let data: any = { ...formDatas.value };
      data.deptName = res.data?.deptName;
      data.orderId = res.data?.orderId;
      data.payStatus = res.data?.payStatus;
      data.registerId = res.data?.registerId;
      data.time = dayjs(new Date()).format('YYYY-MM-DD HH:mm');
      emits('confirm', data);
      visible.value = false;
    } else {
      //ElMessage.error(res.msg);
    }
  });
  // 校验并提交
};
</script>

<style scoped lang="scss">
.register-dialog-form {
  padding: 12px 8px 0 8px;
  margin-top: 51px;
  ::v-deep(.el-form--inline .el-form-item) {
    margin-right: 0;
  }
  ::v-deep(.el-form-item--large) {
    margin-bottom: 15px;
  }
}
.custom-register-form {
  width: 100%;
}
.form-row {
  display: flex;
  gap: 9px;
  margin-bottom: 10px;
}
.form-item {
  margin-bottom: 10px;
}

.form-item-gender {
  width: 67px;
}

.form-item-phone {
  flex: 2;
}

.form-item-age {
  flex: 1;
  min-width: 60px;
}
.form-item-month {
  flex: 1;
  min-width: 60px;
}
.form-row-1 {
  padding-left: 10px;
}
.register-dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.blood-pressure-input-container {
  display: flex;
  align-items: center;
  box-shadow: 0 0 0 1px #dcdcdc inset;
  border-radius: 4px;
  padding-right: 20px;
  padding-left: 1px;
  background: #ffffff;
  margin-left: 10px;
}
.pressure-input {
  flex: 1;
  border: none;
  outline: none;
  width: 60px;
}
.blood-pressure-input-container {
  ::v-deep(.el-input__wrapper:hover) {
    box-shadow: none;
  }
  ::v-deep(.el-input__wrapper) {
    box-shadow: none;
  }
}
.input__prefix {
  position: absolute;
  right: 15px;
  top: 9px;
}
::v-deep(.modal-footer) {
  border: none;
  display: none;
}
</style>
<style scoped lang="scss">
.register-dialog-header-bar {
  display: flex;
  position: absolute;
  width: 100%;
  height: 80px;
  top: 0;
  left: 0;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px 0 18px;

  background: linear-gradient(90deg, #f5fefd 0%, #fbfbfa 100%);
}
.header-bar-left {
  display: flex;
  align-items: center;
}
.tab-btns {
  display: flex;
  border: 1.5px solid #bfe7e4;
  border-radius: 8px;
  background: #f8fefd;
  overflow: hidden;
}
.tab-btn {
  display: flex;
  align-items: center;
        font-size: 18px;

  font-weight: 500;
  color: #18b3ab;
  background: #f8fefd;
  padding: 0 24px;
  height: 36px;
  cursor: pointer;
  border: none;
  transition: background 0.2s, color 0.2s;
}
.tab-btn:not(.active) {
  color: rgba(0, 0, 0, 0.6);
  background: #f8fefd;
}
.tab-btn.active {
  background: #18b3ab;
  color: #fff;
  border-radius: 8px 0 0 8px;
}
.tab-btn + .tab-btn {
  border-left: 1.5px solid #bfe7e4;
  border-radius: 0 8px 8px 0;
}
.tab-icon {
  width: 22px;
  height: 22px;
  margin-right: 6px;
}
.header-bar-right {
  margin-left: auto;
}
.read-card-btn {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #00615b;
  background: #f8fefd;
  border: 1.5px solid #bfe7e4;
  border-radius: 50px;
  padding: 0 24px;
  height: 36px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.2s, color 0.2s;
}
.read-card-btn:hover {
  background: #e6f7f5;
}
::v-deep(.el-form-item__label) {
  height: 46px;
  line-height: 46px;
}
</style>
<style lang="scss">
.register-dialog-header-bar .el-input-group__append,
.el-input-group__prepend {
  padding: 0 8px;
}
.form-item-name2 .el-select__wrapper {
  height: 46px;
  width: 100% !important;
}
.form-item {
  .el-input__prefix {
    display: none;
    height: 46px;
  }
  .el-input__suffix-inner {
    color: #666;
  }
}
</style>
